package com.qlm.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.qlm.common.Define;
import com.qlm.entity.Img;
import com.qlm.service.IImgService;
import com.qlm.tools.Common;
import com.qlm.tools.DateUtils;
import com.qlm.tools.QiniuUtil;
import com.qlm.view.ResultMessage;

public class ImgServiceImpl implements IImgService {
	protected final static Logger logger = LoggerFactory
			.getLogger(ImgServiceImpl.class);

	@Override
	public List<Img> getAllImg(String id) {		
		return Img.dao.find("select id,img_ img,url_ url from t_img where gift_id_ = "+id);
	}

	@Override
	public ResultMessage delImg(Integer id) {
		boolean flg = false;
		if(!Common.isNullOrEmpty(id)){			
			flg = Img.dao.deleteById(id);
			if(flg){
				callCache("cache/updateImg");
				return new ResultMessage(1, "图片删除成功", null);
			}
			return new ResultMessage(0, "图片删除失败", null);
		}
		return new ResultMessage(0, "网络连接错误", null);
	}

	
	/**
	 * 上传图片文件到七牛云
	 * @param imgFile 图片文件
	 * @return
	 */
	private static ResultMessage saveImgFile(UploadFile imgFile) {
			String fileName = Common.getStringFullDate() + imgFile.getFileName(); // 文件名称
	
			try {
				String success = QiniuUtil.upload(imgFile.getFile().getPath(),
						fileName); // 上传到七牛云服务
				if (success != null) {
					imgFile.getFile().delete(); // 如果上传成功，就删除本地服务的图片
					return ResultMessage.setAllMessage(Define.RM_SUCCESS, "上传图片成功。", fileName);
				} else {
					return ResultMessage.setAllMessage(Define.RM_FAIL, "未能将图片上传至七牛云服务器，上传图片失败，请重试或联系网站管理员。");
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				return ResultMessage.setAllMessage(Define.RM_FAIL, "上传图片失败，请重试或联系网站管理员。");
			}		
	}

	@Override
	public ResultMessage saveImg(String gift_id,UploadFile file) {
		ResultMessage rm = saveImgFile(file);
		if(rm.getState() == Define.RM_SUCCESS && Common.isEmptyString((String)rm.getData())){
			Img img = new Img();
			img.set("gift_id_", gift_id).set("img_", QiniuUtil.IMAGEURL+rm.getData().toString()).set("time_",new Date()).save();
			callCache("cache/updateImg");
			return new ResultMessage(1, "图片上传成功", null);
		}
		return new ResultMessage(0, "网络连接错误", null);
	}

	@Override
	@Before(Tx.class)
	public ResultMessage saveUrl(String id, String url) {
		if(!Common.isEmptyString(id) || !Common.isEmptyString(url)){
			return new ResultMessage(0, "网络连接错误", null);
		}
		String[] id_ = id.split(",");
		String[] url_ = url.split(",");
		if(Common.isNullOrEmpty(id_) || Common.isNullOrEmpty(url_) || id_.length != url_.length || id_.length==0){
			return new ResultMessage(0, "网络连接错误", null);
		}		
		for(int i=0;i<id_.length;i++){
			Img img = new Img();
			if(url_[i].equals("null")){
				img.set("id", id_[i]).set("url_", "").update();
			}else{
				img.set("id", id_[i]).set("url_", url_[i]).update();
			}
		}
		callCache("cache/updateImg");
		return new ResultMessage(1, "URL链接保存成功", null);
	}
	
	
	public static void callCache(String type){
		new Thread(new Runnable() {
			public void run() {
				String cacheUrl = PropKit.get("cacheUrl");
				String[] urlArr = cacheUrl.split(",");
				try{						
					for(int i=0;i<urlArr.length;i++){
						if(Common.isEmptyString(urlArr[i])){
							HttpKit.get(urlArr[i] + type);
							logger.info(urlArr[i]+type+"请求发送成功");
						}							
					}
				}catch(Exception e){
					logger.error(e.getMessage(), e);
				}							
			}
		}).start();
}
}
